<?php
class kf extends CI_Controller {
	function index() {
		$this -> pub -> logp('微信多客服', '1-2');
		$da = $this -> pub -> get_setting('微信多客服', 'WechatKF');
		$this -> load -> view('adminx/kf', $da);
	}

	function get() {
		$this -> pub -> logp('微信多客服', '1-2');
		$access_token = $this -> pub -> access_token();
		if ($access_token['type']) {
			$a = file_get_contents('https://api.weixin.qq.com/cgi-bin/customservice/getkflist?access_token=' . $access_token['access_token']);
			$m = json_decode($a, true);
			foreach ($m['kf_list'] as $v) {
				$v['status'] = 0;
				$q = $this -> db -> get_where('plug_kf', array('kf_id' => $v['kf_id']));
				if ($q -> num_rows() > 0) {
					$this -> db -> limit(1);
					$this -> db -> update('plug_kf', $v, array('kf_id' => $v['kf_id']));
				} else {
					$this -> db -> insert('plug_kf', $v);
				}
			}

			$a = file_get_contents('https://api.weixin.qq.com/cgi-bin/customservice/getonlinekflist?access_token=' . $access_token['access_token']);
			$m = json_decode($a, true);
			foreach ($m['kf_online_list'] as $v) {
				$this -> db -> limit(1);
				$this -> db -> update('plug_kf', $v, array('kf_id' => $v['kf_id']));
			}
		}

		if ($this -> input -> post('key')) {
			$this -> db -> like('kf_nick', $this -> input -> post('key'));
		}
		$q = $this -> db -> get_where('plug_kf');
		$state[0] = '不在线';
		$state[1] = 'PC在线';
		$state[2] = '手机在线';
		$state[3] = 'PC+手机';
		$da['content'] = '';

		foreach ($q->result_array() as $v) {
			$da['content'] .= '<tr>';
			$da['content'] .= '<td>' . $v['id'] . '</td>';
			$da['content'] .= '<td><img width="48" src="' . ($v['kf_headimgurl'] ? $v['kf_headimgurl'] : '/mex/lance/img/tx.jpg') . '" /></td>';
			$da['content'] .= '<td>' . $v['kf_nick'] . '</td>';
			$da['content'] .= '<td>' . $v['kf_account'] . '</td>';
			$da['content'] .= '<td>' . $state[$v['status']] . '</td>';
			$da['content'] .= '</tr>';
		}
		$da['type'] = 1;
		echo json_encode($da);
	}

}
?>